<template>
  <div style="padding:15px;">
    <el-form ref="queryFrom" :inline="true" :model="queryFrom" class="demo-form-inline">
      <el-form-item prop="goodsSn">
        <el-input v-model="queryFrom.goodsSn" placeholder="商品编号" prefix-icon="el-icon-search" maxlength="10" class="el-input--mini" />
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="queryFrom.name" placeholder="商品名称" prefix-icon="el-icon-search" maxlength="10" class="el-input--mini" />
      </el-form-item>
      <el-form-item prop="isOnSale" prefix-icon="el-icon-search" class="el-input--mini">
        <el-select v-model="queryFrom.isOnSale" clearable placeholder="是否上架" class="el-input--mini">
          <el-option
            v-for="item in onSaleOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select></el-form-item>

      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-search" @click="queryShopGoods">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-delete" @click="onReset('queryFrom')">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-plus" @click="onAddKeyword">添加</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      lazy
      element-loading-text="拼命加载中"
      :row-style="{height:'5px'}"
      :cell-style="{padding:'0px'}"
      @expand-change="expandChange"
      @current-change="toggleRowExpansion"
    >
      >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand el-form-item--medium">
            <el-form-item label="宣传画廊">
              <el-image v-for="pic in imagesView" :key="pic" :src="pic.url" class="el-form-item__content" style="width:80px;margin-right:10px;" />
            </el-form-item>
            <el-form-item label="商品介绍">
              <span>{{ props.row.brief }}</span>
            </el-form-item>
            <el-form-item label="商品单位">
              <span>{{ props.row.unit }}</span>
            </el-form-item>
            <el-form-item label="关键字">
              <span>{{ props.row.keywords }}</span>
            </el-form-item>
            <el-form-item label="商品分类 ID">
              <span>{{ props.row.categoryId }}</span>
            </el-form-item>
            <el-form-item label="品牌商 ID">
              <span>{{ props.row.brandId }}</span>
            </el-form-item>

            <el-form-item label="当前价格 /元">
              <span> {{ props.row.retailPrice | priceFilter }}</span>
            </el-form-item>

            <el-form-item label="上架状态">
              <span>{{ props.row.isOnSale ===1?'已上架':'已下架' }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        prop="id"
        label="ID"
        sortable
        width="100"
      />
      <el-table-column
        prop="goodsSn"
        label="商品编号"
        width="130"
        align="center"
      />
      <el-table-column
        prop="name"
        label="商品名称"
        width="380"
        align="center"
      />
      <el-table-column prop="picUrl" align="center" label="商品主图" width="150px">
        <template slot-scope="scope">
          <el-image :src="scope.row.picUrl" style="width: 30%;" @click="onView(scope.row)">
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="counterPrice" align="center" label="专柜价格 /元" width="150px">

        <template slot-scope="scope">
          {{ scope.row.counterPrice | priceFilter }}
        </template>
      </el-table-column>
      <el-table-column prop="retailPrice" align="center" label="当前价格 /元" width="150px">
        <template slot-scope="scope">
          {{ scope.row.retailPrice | priceFilter }}
        </template>
      </el-table-column>

      <el-table-column prop="deleted" align="center" label="上架状态" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isOnSale | tagTypeFilter">
            {{ scope.row.isOnSale | statusfilters }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="操作" align="center">
        <template slot-scope="scope">
          <div>
            <el-button type="primary" class="el-button--mini" size="small" icon="el-icon-edit" @click="onEdit(scope.row)">
              编辑

            </el-button>
            <el-button type="danger" class="el-button--mini" size="small" icon="el-icon-close" @click="onDeleted(scope.row)">{{ scope.row.isOnSale ===0? '上架':'下架' }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :total="page.totalCount"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      title="商品详情"
      :visible.sync="dialogVisible"
      width="30%"

      @close="handleClose"
    >
      <div v-for="(item,key) in imagesView" :key="key">
        <el-image :src="item.url" style="width:100%" />
      </div>
    </el-dialog>

  </div>
</template>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>

<script>
import { queryShopGoods, goodSoldOut } from '@/api/goods/index'

export default {
  filters: {

    tagTypeFilter(status) {
      return status === 1 ? 'success' : 'gray'
    },
    priceFilter(value) {
      return value / 100
    },
    isDefaultfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 0) {
          return '否'
        }
        if (val === 1) {
          return '是'
        }
      }
    },
    statusfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 1) {
          return '已上架'
        }
        if (val === 0) {
          return '已下架'
        }
      }
    }

  },

  data() {
    return {
      fits: ['fill', 'contain', 'cover', 'none', 'scale-down'],
      options: [{
        value: 0,
        label: '正常'
      }, {
        value: 1,
        label: '禁用'
      }],
      onSaleOption: [{
        value: 0,
        label: '已下架'
      }, {
        value: 1,
        label: '已上架'
      }],
      queryFrom: {
        name: '',
        goodsSn: '',
        isOnSale: ''
      },
      from: {
        id: '',
        name: '',
        desc: '',
        picUrl: '',
        floorPrice: '',
        defaultCategoryId: '',
        address: '',
        fetchTimeRules: '',
        goodsSn: ''

      },
      page: {
        'rowCount': 10,
        'currentPage': 1,
        'pageSize': 10,
        'pageCount': 2,
        'totalCount': 0,
        'orderBy': null,
        'outofBounds': false,
        'limitStart': 0
      },
      tableData: [],
      imagesView: [],
      refresh: 0,
      dialogFormVisible: false,
      title: '',
      isAdd: false,
      formLabelWidth: '130px',
      categoryList: [],
      rules: {
        name: [{ required: true, message: '请填写品牌商名称', trigger: 'blur' }],
        //  defaultCategoryId: [{ type: 'array', required: true, message: '请选择品牌商类目', trigger: 'change' }],
        desc: [{ required: true, message: '请填写品牌商介绍', trigger: 'change ' }],
        picUrl: [{ required: true, message: '请填写品牌商图片', trigger: 'change ' }],
        floorPrice: [{ required: true, message: '请填写底价', trigger: 'blur' }],
        address: [{ required: true, message: '请填写自提地址', trigger: 'blur' }],
        fetchTimeRules: [{ required: true, message: '请填写提货时间', trigger: 'blur' }]
      },
      loading: true,
      dialogVisible: false
    }
  },
  created() {
    this.queryShopGoods()
  },
  methods: {

    queryShopGoods() {
      this.loading = true
      const queryPage = { page: this.page }
      var qq = Object.assign(queryPage, this.queryFrom)
      queryShopGoods(qq).then(response => {
        this.loading = false
        this.tableData = response.data.list

        this.page = response.data.page
      })
    },
    onAddKeyword() {
      this.dialogFormVisible = true
      this.title = '新增'
      this.isAdd = true
      this.clearForm()
      this.categoryList = []
    },
    onEdit(row) {
      this.$router.push({ path: '/goods/edit/index', query: { id: row.id }})
    },
    onSubmitShopBrand(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          if (!this.isAdd) {
            this.from.deleted = null
            if (this.from.fetchTimeRules !== null) {
              this.from.fetchTimeRules = this.from.fetchTimeRules[0] + ' - ' + this.from.fetchTimeRules[1]
            }
            const obj = this.$refs['cascaderHandle'].getCheckedNodes()
            this.from.defaultCategoryId = obj[0].data.value
            // updateShopBrand(this.from).then(response => {
            //   this.$message.success(response.msg)
            //   this.dialogFormVisible = false
            //   this.clearForm()
            //   this.queryShopBrand()
            // })
          } else {
            this.from.deleted = false
            if (this.from.fetchTimeRules !== null) {
              this.from.fetchTimeRules = this.from.fetchTimeRules[0] + ' - ' + this.from.fetchTimeRules[1]
            }
            const obj = this.$refs['cascaderHandle'].getCheckedNodes()
            this.from.defaultCategoryId = obj[0].data.value
            // addShopBrand(this.from).then(response => {
            //   this.$message.success(response.msg)
            //   this.dialogFormVisible = false
            //   this.queryShopBrand()
            //   this.clearForm()
            // })
          }
        } else {
          return false
        }
        this.$refs[formName].clearValidate()
      })
    },
    onDeleted(row) {
      const title = row.deleted === 0 ? '删除' : '恢复'
      this.$confirm('确认要' + title + '该品牌商: ' + row.name + ' 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearForm()
        this.from.id = row.id
        this.from.deleted = row.deleted === 0 ? 1 : 0
        this.from.goodsSn = row.goodsSn

        goodSoldOut(this.from).then(response => {
          this.$notify({ title: response.msg, duration: 1000, type: response.code === 200 ? 'success' : 'error' })
          this.clearForm()
          this.queryShopGoods()
        })
      }).catch(() => {
      })
    },
    onView(row) {
      this.imagesView = []
      // this.imagesView = row.gallery.replace('[', '').replace(']', '').replace('"', '').replace('"', '').split(',')
      row.gallery.split(',').forEach(element => {
        this.imagesView.push({

          url: element.replace('[', '').replace(']', '').replace('"', '')

        })
      })

      this.dialogVisible = true
    },
    onReset(formName) {
      this.$refs[formName].resetFields()
      this.queryFrom.name = null
    }, handleSizeChange(val) {
      this.page.pageSize = val
      this.queryShopGoods()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.queryShopGoods()
    },
    cancelChange(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].clearValidate()
      this.clearForm()
    },
    clearForm() {
      this.from.id = null
      this.from.name = null
      this.from.desc = null
      this.from.picUrl = null
      this.from.floorPrice = null
      this.from.defaultCategoryId = null
      this.from.address = null
      this.from.fetchTimeRules = null
      this.from.goodsSn = null
      this.value = null
      this.imagesView = []
    },
    handleChange(value) {
    },
    restForm() {
      this.$refs.from.resetFields()
    },
    handleClose() {
      this.dialogVisible = false
    },
    expandChange(row, value) {
      this.imagesView = []
      row.gallery.split(',').forEach(element => {
        this.imagesView.push({

          url: element.replace('[', '').replace(']', '').replace('"', '')

        })
      })
    },
    toggleRowExpansion(row) {

    }
  }
}
</script>
